package com.tfswue.yhj.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
//开启websecurity配置
@EnableWebSecurity
public class SecurityConfig {
    //配置密码加密器（必须）

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();  //使用BCrypt 强哈希加密
    }

    //配置用户存储（内存方式，生产环境需连接数据库）
    @Bean
    public UserDetailsService userDetailsService(){
        //创建两个测试用户
        UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder().encode("pass")) //密码必须加密
                .roles("USER") //分配角色
                .build();
        UserDetails admin = User.builder()
                .username("adimin")
                .password(passwordEncoder().encode("admin")) //密码必须加密
                .roles("ADMIN", "USER") //  可分配多个角色
                .build();
        return new InMemoryUserDetailsManager(user, admin);
    }
    //核心安全配置（HTTP 请求过滤规则）
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/","/index").permitAll() //允许根路径匿名访问
                        .requestMatchers("/public/**").permitAll()   //公共路径无需认证
                        .requestMatchers("/admin/**").hasRole("ADMIN") //仅管理员可访问
                        .anyRequest().authenticated()   //其他所有请求需认证
                )
                .formLogin(form -> form
                        .loginPage("/index.html")       //与实际文件路径一致
                        .loginProcessingUrl("/login")   //处理登录的URL
                        .defaultSuccessUrl("/public/hello") //登陆成功后固定跳转到此路径
                        .permitAll()
                )
                .logout(logout -> logout
                        .logoutSuccessUrl("/public/goodbye")    //登出后跳转地址
                        .permitAll()
                )
                .csrf(csrf -> csrf.disable());     //禁用CSRF保护（开发环境方便测试）
        return http.build();
    }
}
